<?php

namespace pmvc\data\sql\pdo;

use pmvc\tx\Transaction;
use Exception;
use PDO;

class PDOTransaction
	implements Transaction {

	private $started 	= false;
	private $committed	= false;
	private $rolledBack	= false;
	private $autoCommit	= false;

	/**
	 * @var PDO
	 */
	private $pdo = null;

	public function __construct(PDO $pdo) {
		$this->pdo = $pdo;
	}

	public function setAutoCommit($autoCommit) {
		if ($this->started) {
			throw new Exception(
				"Cant set auto commit because transaction is already started");
		}
		$this->autoCommit = ($autoCommit===TRUE || $autoCommit==1);
	}

	public function isAutoCommit() {
		return $this->autoCommit;
	}

	public function isCommited() {
		return $this->committed;
	}

	public function isRolledBack() {
		return $this->rolledBack;
	}

	public function start() {
		if ($this->started) {
			throw new Exception(
				"Cant start transaction because it's already started");
		}
		$this->pdo->setAttribute(PDO::ATTR_AUTOCOMMIT, $this->autoCommit);
		$this->pdo->beginTransaction();
		$this->started = true;
	}

	public function commit() {
		$this->pdo->commit();
		$this->committed = true;
	}

	public function rollback() {
		$this->pdo->rollBack();
		$this->rolledBack = true;
	}

}

?>